// 引入我们刚刚创建的index.js api文件
import axiosApi from '@/api/index.js'
import { Message } from 'element-ui'

import langZh from '@/locales/zh.json'
import langEN from '@/locales/en.json'
import langDe from '@/locales/de.json'
import langEs from '@/locales/es.json'
import langFr from '@/locales/fr.json'
import langJa from '@/locales/ja.json'
import langKo from '@/locales/ko.json'
import langPt from '@/locales/pt.json'
import langTw from '@/locales/tw.json'
import langVi from '@/locales/vi.json'
const messages = {
  zh: { ...langZh },
  en: { ...langEN },
  de: { ...langDe },
  es: { ...langEs },
  fr: { ...langFr },
  ja: { ...langJa },
  ko: { ...langKo },
  pt: { ...langPt },
  tw: { ...langTw },
  vi: { ...langVi },
}

export default function ({ $axios, store, router, $cookies }, inject) {
  function axiosConfig($axios) {
    let requestConfig = {}

    // 基本配置
    $axios.defaults.timeout = 10000

    $axios.defaults.validateStatus = function (status) {
      return status >= 200 && status <= 500
    }

    $axios.defaults.withCredentials = true

    if (process.env.NODE_ENV !== 'development') {
      $axios.setBaseURL(
        process.browser ? 'https://www.toolify.ai' : 'http://api.toolify.ai'
      )
    }

    // 设置请求拦截
    $axios.onRequest((config) => {
      requestConfig = {
        baseURL: config.baseURL,
        url: config.url,
        method: config.method,
        data: config.data,
        headers: config.headers,
        params: config.params,
      }

      //console.log(process.env.MODE, process.env.NODE_ENV)

      config.startTime = new Date().getTime()
      config.headers['Content-Type'] = 'application/json'
      config.headers['locale'] = store.state.locale
      config.headers['timezone'] = Intl.DateTimeFormat().resolvedOptions()
        .timeZone
        ? Intl.DateTimeFormat().resolvedOptions().timeZone
        : ''

      return config
    })
    // 设置响应拦截
    $axios.onResponse((response) => {
      response.config.endTime = new Date().getTime()
      const status = response.status

      if (status === 200) {
        if (response.data.code === 401) {
          store.commit('SET_ISLOGIN', false)

          if (
            process.browser &&
            window &&
            window.$nuxt &&
            window.$nuxt.$router
          ) {
            window.$nuxt.$router.push({
              path:
                store.state.locale === 'en' || !store.state.locale
                  ? `/login`
                  : `/${store.state.locale}/login`,
            })
          }
        } else if (response.data.code !== 200 && process.browser) {
          Message.closeAll()

          if (response.config.dealErrorSelf) {
            return false
          }

          let locale = store.state.locale
          let msg =
            locale &&
            messages[locale] &&
            messages[locale][`error_${response.data.code}`]
              ? messages[locale][`error_${response.data.code}`]
              : response.data.message ||
                'There is a problem with the network. Please refresh and try again later'

          Message({
            message: msg,
            type: 'error',
            offset: 120,
            duration: 2000,
          })
        }
        //console.log(JSON.stringify(response.data))
        return response.data
      } else {
        if (process.browser && !response.config.dealErrorSelf) {
          Message.closeAll()
          Message({
            message:
              'There is a problem with the network. Please refresh and try again later',
            type: 'error',
            offset: 120,
            duration: 2000,
          })
        }
      }
    })

    // axios错误处理
    $axios.onError((error) => {
      const { config } = error
      if (process.browser && !config.dealErrorSelf) {
        Message.closeAll()
        //超时提示
        if (error.message === 'timeout of 30000ms exceeded') {
          Message({
            message:
              'There is a problem with the network. Please refresh and try again later',
            type: 'error',
            offset: 120,
            duration: 2000,
          })
        } else {
          Message({
            message:
              'There is a problem with the network. Please refresh and try again later' ||
              'Error',
            type: 'error',
            offset: 120,
            duration: 2000,
          })
        }
      }
    })
    // 最后返回$axios对象
    return $axios
  }
  inject('axiosApi', axiosApi(axiosConfig($axios.create())))
}
